// page/component/orders/orders.js
const app = getApp();
const { request } = require('../../../utils/request');

Page({
  data: {
    orders: []
  },

  onLoad: function (options) {
    this.loadOrders();
  },
  onShow() {
    const paymentSuccess = wx.getStorageSync('paymentSuccess');
    if (paymentSuccess) {
      this.loadOrders();
      // 清除支付成功标志
      wx.removeStorageSync('paymentSuccess');
    }
  },

  async loadOrders() {
    try {
      const res = await request({
        url: '/order',
        method: 'GET',
        showLoading: true
      });

      if (res.code === 2000) {
        this.setData({ orders: res.data.items });
      } else {
        wx.showToast({
          title: '加载订单失败',
          icon: 'none'
        });
        console.error('加载订单失败:', res.message);
      }
    } catch (error) {
      wx.showToast({
        title: '请求出错',
        icon: 'none'
      });
      console.error('加载订单请求出错:', error);
    }
  },

  // 跳转到付款界面
  navigateToPayment(e) {
    const orderId = e.currentTarget.dataset.id;
    const totalPrice = e.currentTarget.dataset.total;
    wx.navigateTo({
      url: `/page/component/payment/payment?orderId=${orderId}&totalPrice=${totalPrice}`
    });
  },

  // 取消订单
  async cancelOrder(e) {
    const orderId = e.currentTarget.dataset.id;
    try {
      wx.showLoading({ title: '取消中...' });
      const res = await request({
        url: `/order/${orderId}/cancel`,
        method: 'DELETE'
      });
      wx.hideLoading();
      if (res.code === 2000) {
        wx.showToast({ title: '取消成功' });
        this.loadOrders();
      } else {
        wx.showToast({ title: res.message || '取消失败', icon: 'none' });
      }
    } catch (error) {
      wx.hideLoading();
      wx.showToast({ title: '请求失败，请稍后重试', icon: 'none' });
      console.error('取消订单请求出错:', error);
    }
  },

  // 标记为已送达
  async markAsDelivered(e) {
    const orderId = e.currentTarget.dataset.id;
    try {
      wx.showLoading({ title: '标记中...' });
      const res = await request({
        url: `/order/${orderId}/delivered`,
        method: 'POST'
      });
      wx.hideLoading();
      if (res.code === 2000) {
        wx.showToast({ title: '标记成功' });
        this.loadOrders();
      } else {
        wx.showToast({ title: res.message || '标记失败', icon: 'none' });
      }
    } catch (error) {
      wx.hideLoading();
      wx.showToast({ title: '请求失败，请稍后重试', icon: 'none' });
      console.error('标记已送达请求出错:', error);
    }
  }
});